package com.ruoyi.api.balance;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.IOUtil;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.ListDetail;
import com.ruoyi.system.domain.SupplyUser;
import com.ruoyi.system.mapper.OrderListMapper;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.IOrderListService;
import com.ruoyi.system.service.ISupplyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 电子秤请求
 */
@Controller
@RequestMapping("/balance")
public class BalanceCtrl extends BalanceBaseCtrl{

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IOrderListService orderListService;

    @Autowired
    private ISupplyUserService supplyUserService;
    @Autowired
    private OrderListMapper orderListMapper;

    /**
     * 退出
     * @return
     */
    @ResponseBody
    @RequestMapping("/logOut")
    public AjaxResult logOut(){
        //清除TOKEN
        clearToken();
        return AjaxResult.success();
    }

    /**
     * 登录
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestParam("phone")String phone,@RequestParam("password")String password){

        //查询用户是否存在
        SupplyUser user = new SupplyUser();
        user.setPhone(phone);
        user.setPwd(IOUtil.MD5(password));
        List<SupplyUser> list = supplyUserService.selectSupplyUserList(user);
        if(list.size() == 0){
            return AjaxResult.error("账号或密码错误");
        }
        user = list.get(0);
        if(!user.getStatus().equals("Y")){
            return AjaxResult.error("用户已被禁用");
        }
        //登录成功
        String token = IOUtil.MD5(user.getPhone() + user.getPwd() + System.currentTimeMillis());
        //存储登录信息
        setLoginSupplyUser(user,token);
        JSONObject data = new JSONObject();
        data.put("token",token);
        data.put("supply",user.getSupplyName());

        return AjaxResult.success(data);
    }



    /**
     * 获取设备信息
     * @return
     */
    @RequestMapping("/getDeviceInfo")
    @ResponseBody
    public AjaxResult getDeviceInfo(){
        Device device = getRequstDevice();
        if(device == null){return AjaxResult.error("MAC信息错误");}
        //测试数据
        return AjaxResult.success(device);
    }

    /**
     * 查询我的待入库商品
     * @return
     */
    @RequestMapping("/getMyListGoods")
    @ResponseBody
    public TableDataInfo getMyListGoods(){

        Device device = getRequstDevice();
        if(device == null){
            TableDataInfo data = new TableDataInfo();
            data.setCode(100);
            data.setMsg("设备信息有误");
            return data;
        }

        long shopId = device.getShopId();
        long supplyId = getLoginSupplyUser().getSupplyId();

        //查找带录入的商品
        ListDetail detail = new ListDetail();
        detail.setStatus("0");
        Map<String,Object> map=new HashMap<>();
//        map.put("statusin","('0','1','2','3')");
        map.put("statusin","('3')");//目前只显示待入库的商品
        map.put("supplyId",supplyId);
        map.put("shopId",shopId);
//        map.put("day", IOUtil.getdate("yyyy-MM-dd"));//正式需要取消注释
        detail.setParams(map);
        List<ListDetail> list= orderListService.getListGoods(detail);
        return getDataTable(list);
    }

    /**
     * 入库
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping("/storeIn")
    public AjaxResult storeIn(@RequestBody JSONObject data){
        //{"data":[{"devicePic":"http://124.221.250.129/wms/profile/upload/2025/10/09/白醋20251009092536_20251009092540A010.jpg","goodsNum":5.0,"id":57,"localImage":"2025年10月09日/白醋20251009092536.jpg","success":true}]}
        JSONArray array = data.getJSONArray("data");
        Device device = getRequstDevice();
        List<ListDetail> list = new ArrayList<>();
        Set<Long> idset = new HashSet<>();
        for(int i=0;i<array.size();i++) {
            JSONObject obj = array.getJSONObject(i);
            Long id = obj.getLong("id");
            Double goodsNum = obj.getDouble("goodsNum");
            String devicePic = obj.getString("devicePic");
            String localImage = obj.getString("localImage");
            ListDetail detail = orderListService.selectListDetailById(id);
            idset.add(id);
            detail.setGoodsNumReal(goodsNum);
            detail.setTotalPriceReal(goodsNum*detail.getRealPrice());
            detail.setStatus("1");
            detail.setDevicePic(devicePic);
            detail.setDevidId(device.getId());
            list.add(detail);
        }
        AjaxResult result = orderListService.deviceStockIn(list,device);
        //如果操作成功，更新订单总金额
        if(result.isSuccess()){
            StringBuffer ids = new StringBuffer("(");
            for(Long id:idset){
                ids.append(id+",");
            }
            ids.deleteCharAt(ids.length()-1);
            ids.append(")");
            orderListMapper.updateOrderPrice(ids.toString());
        }

        return result;
    }

    //定时任务，更新订单状态
    public void updateList(){
        System.out.println("强制更新订单状态任务");
        orderListMapper.updateOrderListStatusForced31();
        orderListMapper.updateOrderListStatusForced4();
    }

}
